package com.mystudy.concurrent.base;

import javafx.concurrent.Worker;

/**
 * TODO: 关闭线程的方式
 * 执行线程里面创建一个runner守护线程，守护线程用来执行对应的操作，执行线程结束，守护线程就会结束
 * @author acy
 * @since 2019/05/13 11:21
 */
public class ThreadCloseTest {
	public static void main(String[] args) {

	}

}

class ThreadService {
	private Thread execute;

	private boolean isFinish = false;

	public void execute(Runnable task) {
		execute = new Thread(() -> {
			Thread thread = new Thread(task);
			thread.setDaemon(true);
			thread.start();
			try {
				//避免守护线程还没有执行父线程就结束了
				thread.join();
				isFinish = true;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		});
		execute.start();
	}

	public void shoutDown(long mills) {
		long currentTime = System.currentTimeMillis();
		while (!isFinish) {
			if ((System.currentTimeMillis() - currentTime) >= mills) {
				System.out.println("任务超时，结束任务");
				execute.interrupt();
				break;
			}
			try {
				execute.sleep(1);
			} catch (InterruptedException e) {
				System.out.println("执行线程被打断");
				e.printStackTrace();
				break;
			}
		}
		isFinish = false;
	}

}
